package com.example.administrator.myjdlc.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;

import com.example.administrator.myjdlc.R;
import com.example.administrator.myjdlc.activity.MainActivity;
import com.example.administrator.myjdlc.activity.ProductDetailActivity;
import com.example.administrator.myjdlc.adapter.ProductMainHotAdapter;
import com.example.administrator.myjdlc.bean.ProductMainEntity;
import com.example.administrator.myjdlc.bean.ServiceData;
import com.example.administrator.myjdlc.common.Code;
import com.example.administrator.myjdlc.common.Code.HttpSetting;
import com.example.administrator.myjdlc.common.Const;
import com.example.administrator.myjdlc.net.BackData;
import com.example.administrator.myjdlc.net.CanNetServiceInter;
import com.example.administrator.myjdlc.net.NetLoadListener;
import com.example.administrator.myjdlc.net.NetService;
import com.example.administrator.myjdlc.utils.CommonUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;


/**
 * Created by Administrator on 2017/4/24.
 */

public class FinancesFragement extends BaseFragment {

    /**
     * 服务器返回的信息
     */
    private static final int SERVICE_MESSAGE=0;
    /**
     * 网络错误
     */
    private static final int NET_ERROR=1;
    /**
     * 初始化数据
     */
    private static final int GET_FINANCE_MAIN=1001;
    /**
     * 消息数据
     */
    private static final int MESSAGE_DATA=3;
    private NetService netService;
    private MainActivity activity;
    private ProductMainEntity entity;
    private Handler handler = new Handler() {
        @SuppressWarnings("static-access")
        @SuppressLint("NewApi")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case NET_ERROR:
                    if (isAdded()) {
//                        toast.setIcon(R.drawable.ic_toast_error);
//                        toast.show(getString(R.string.network_failure));
//                        activity.isLoadDataSuccess=false;
//                        activity.isload=false;
                    }
                    break;
                case GET_FINANCE_MAIN:
                    BackData result =(BackData) msg.obj;
                    Gson gson = new GsonBuilder().disableHtmlEscaping().create();
                    try{
                        ServiceData data = gson.fromJson(result.getObject().toString(), ServiceData.class);
                        if (data.getCode() == Code.ServiceCode.SUCCESS) {
                            // 返回字符串
                            String json = String.valueOf(result.getObject());
                            entity = gson.fromJson(json, ProductMainEntity.class);
                            //初始化理财类信息成功
                            if (entity != null) {
//                                activity.productMainEntity= entity;
//                                getMessageInNet();
                                setDate2View(entity);
//                                activity.isload=false;
                            }
                        } else {
                            if(msg!=null&&msg.obj!=null){
                                //toast.setIcon(R.drawable.ic_toast_error);
                                //toast.show((String)msg.obj);
//                                activity.isLoadDataSuccess=false;
//                                activity.isload=false;
                            }
                        }
                    }catch (Exception e){

                    }
                    break;
                case MESSAGE_DATA:
                    //加载消息信息成功
//                    if(messageEntity!=null){
//                        activity.messageEntity=messageEntity;
//                        showMessageCount(activity.messageEntity);
//                        activity.isLoadDataSuccess=true;
//                    }
                    break;
            }
        }
    };
    private Context ctx;
    private View headView;
    private RecyclerView productList;
    private ProductMainHotAdapter productMainHotAdapter;


    @Override
    public View initView(LayoutInflater inflater) {
        ctx = getActivity();
        activity = (MainActivity) getActivity();
        netService = NetService.getInstance();
        entity = new ProductMainEntity();
        view = inflater.inflate(R.layout.fragment_finances_main, null);
        productList = (RecyclerView) view.findViewById(R.id.product_list);
        headView = inflater.inflate(R.layout.product_main_login,null);

        //判断是否是登陆了。加载不一样的头布局
        inflaterHeaderView(inflater, false);
//        if (activity.PAGE_TYPE==1) {
//            // 如果登陆了
//            inflaterHeaderView(inflater, true);
//        } else {
//            // 如果没登陆
//            inflaterHeaderView(inflater, false);
//        }
        return view;

    }

    private void inflaterHeaderView(LayoutInflater inflater, boolean b) {
        productMainHotAdapter = new ProductMainHotAdapter(ctx, entity.data.products);
        productMainHotAdapter.setFirstOnly(false);
        productMainHotAdapter.addHeaderView(headView);
        productList.setLayoutManager(new LinearLayoutManager(getContext()));
        productList.setAdapter(productMainHotAdapter);
    }

    public void initView() {

    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData(Bundle var1) {
        getInitDataInNet();
    }

    private void setDate2View(final ProductMainEntity entity) {



        productList.setLayoutManager(new LinearLayoutManager(getContext()));
//        productList.setAdapter(productMainHotAdapter);
//        productMainHotAdapter.notifyDataSetChanged();
        productMainHotAdapter = new ProductMainHotAdapter(ctx, entity.data.products);
        productMainHotAdapter.setFirstOnly(false);
        productMainHotAdapter.addHeaderView(headView);
        productMainHotAdapter.setOnItemClickListener(new ProductMainHotAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent();
                intent.putExtra("product",entity.data.products.get(position ));
                intent.putExtra("pay_limit",entity.data.products.get(position ).attributes[0]);
                intent.setClass(ctx, ProductDetailActivity.class);
                startActivity(intent);
            }
        });
        productList.setLayoutManager(new LinearLayoutManager(getContext()));
        productList.setAdapter(productMainHotAdapter);

    }


    /**
     * 获取初始化数据
     */
    public void getInitDataInNet() {
        Message msg =Message.obtain();
        if(Code.NetworkStatus.NO_NET== CommonUtils.getAPNType()){
            msg.what=NET_ERROR;
            handler.sendMessage(msg);
            return;
        }
        netService.getIsRunning(new CanNetServiceInter() {
            @Override
            public void canRequst() {
                // 请求网络
                netService.setHttpMethod(HttpSetting.GET_MODE);
                netService.clearParams();
                netService.setUrl(Const.HttpConst.GET_FINANCE_MAIN);
                netService.loader(new NetLoadListener() {
                    @Override
                    public void onloaderListener(BackData result) {
                        Message message =Message.obtain();
                        if (result != null && result.getObject() != null) {
                            if (result.getNetResultCode() == Code.NetStatusCode.SUCCESS) {
                                message.what=GET_FINANCE_MAIN;
                                message.obj=result;
                            } else {
                                // 网络异常
                                message.what=NET_ERROR;
                            }
                            handler.sendMessage(message);
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }



}
